from typing import List

from sqlalchemy.orm import Session

from server.app.cloud_ide.model import IdeEnvironment
from server.app.cloud_ide.schema.ide_environment.request.ide_environment_create_request import \
    IdeEnvironmentCreateRequest
from server.app.cloud_ide.schema.ide_environment.request.ide_environment_update_request import \
    IdeEnvironmentUpdateRequest
from server.framework.core.logger import logger


class IdeEnvironmentService:
    def find_ide_environment_by_name(self, db: Session, name: str) -> IdeEnvironment:
        entity = db.query(IdeEnvironment).filter(name == IdeEnvironment.name).first()
        return entity

    def get_ide_environment_by_id(self, db: Session, id: str) -> IdeEnvironment:
        entity = db.query(IdeEnvironment).filter(id == IdeEnvironment.id).one()
        return entity

    def get_all_environments(self, db: Session) -> List[IdeEnvironment]:
        return db.query(IdeEnvironment).all()

    def get_ide_environment_list(self, db: Session, name: str, page_size: int,
                                 current_page: int):
        query = db.query(IdeEnvironment)
        if name:
            query = query.filter(IdeEnvironment.name.like("%" + name + "%"))
        total = query.count()
        items = query.limit(page_size).offset((current_page - 1) * page_size).all()
        return items, total

    def update_ide_environment(self, db: Session, data: IdeEnvironmentUpdateRequest) -> bool:
        try:
            db.query(IdeEnvironment).filter(IdeEnvironment.id == data.id).update(data.dict())
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def delete_ide_environment(self, db: Session, ids: list) -> bool:
        try:
            db.query(IdeEnvironment).filter(IdeEnvironment.id.in_(ids)).delete(synchronize_session=False)
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def create_ide_environment(self, db: Session, data: IdeEnvironmentCreateRequest) -> bool:
        try:
            entity = IdeEnvironment(**data.dict())
            db.add(entity)
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False
